package org.example.ams.util;

import cn.hutool.json.JSONUtil;
import org.example.ams.entity.system.SysUser;
import org.example.ams.service.system.ILoginService;
import org.example.ams.service.system.ISysUserService;
import org.example.common.cache.CacheUtils;
import org.example.common.constant.RedisConstant;
import org.example.security.util.LoginUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统工具类
 * @author cheval
 */
@Component
public class SystemUtils {

    @Autowired
    private ILoginService loginService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取登录用户信息
     * @return
     */
    public SysUser loginUser() {
        String username = LoginUtils.currentLoginUser().getUsername();
        // 1. 先查询缓存，没有查到再查询数据库
        String key = RedisConstant.LOGIN_USER_INFO_KEY_PREFIX + username;
        String jsonStr = redisTemplate.opsForValue().get(key);
        if (jsonStr == null) {
            // 1.1 没有获取到，查询数据库，并写缓存
            SysUser sysUser = loginService.querySysUserByUserName(username);
            redisTemplate.opsForValue()
                    .set(key,JSONUtil.toJsonStr(sysUser),
                            RedisConstant.LOGIN_USER_INFO_CACHE_TIME, RedisConstant.LOGIN_USER_INFO_CACHE_TIMEUNIT);
            return sysUser;
        } else {
            // 1.2 获取到，直接返回
            return JSONUtil.toBean(jsonStr, SysUser.class);
        }
    }

    /**
     * 获取所有用户信息
     * @return
     */
    public List<SysUser> getAllUser() {
        CacheUtils<String,SysUser> cacheUtils =
                new CacheUtils<String,SysUser>(redisTemplate, RedisConstant.USERS_INFO_CACHE_TIME,RedisConstant.USERS_INFO_CACHE_TIME_UNIT);
        return cacheUtils.query(() -> {
            return userService.queryAll();
        },SysUser.class,RedisConstant.USERS_INFO_KEY);
    }


    /**
     * 获取用户id到用户名的映射，方便数据转换
     * @return
     */
    public Map<Integer,String> getUserIdToNameMapper(){
        Map<Integer,String> mapper = new HashMap<>();
        List<SysUser> allUser = getAllUser();
        for (SysUser sysUser : allUser) {
            mapper.put(sysUser.getUserId(),sysUser.getUsername());
        }
        return mapper;
    }
}
